package edu.ccut.saturn.component.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import edu.ccut.saturn.component.IMenuInfo;
import edu.ccut.saturn.component.IMuneItemInfo;
import edu.ccut.saturn.component.SaturnMenuManager;

public class SaturnMenuInfo implements IMenuInfo {

	private String bundlesSymbolicName;

	private List<IMuneItemInfo> menuItemInfos;

	private List<IMuneItemInfo> roots;

	public SaturnMenuInfo(String bundlesSymbolicName) {
		this.bundlesSymbolicName = bundlesSymbolicName;
		this.menuItemInfos = new ArrayList<IMuneItemInfo>();
	}

	public SaturnMenuInfo(IMenuInfo menuInfo) {
		this(menuInfo.getBundleSymbolicName());
		List<IMuneItemInfo> menuItemList = menuInfo.getMenuItemInfos();

		if (menuItemList != null && menuItemList.size() > 0) {

			for (IMuneItemInfo muneItemInfo : menuItemList) {
				SaturnMenuItemInfo saturnMenuItemInfo = new SaturnMenuItemInfo(
						muneItemInfo);

				this.menuItemInfos.add(saturnMenuItemInfo);
			}
			this.initialMenuItemRoots();
		}
	}

	public String getBundleSymbolicName() {
		return this.bundlesSymbolicName;
	}

	public void setBundleSymbolicName(String bundlesSymbolicName) {
		this.bundlesSymbolicName = bundlesSymbolicName;
	}

	public List<IMuneItemInfo> getMenuItemInfos() {
		return this.menuItemInfos;
	}

	public void initMenuInfo(List<IMuneItemInfo> menuItemInfos) {
		this.menuItemInfos = menuItemInfos;

		if (this.menuItemInfos != null) {

			for (IMuneItemInfo itemInfo : this.menuItemInfos) {
				itemInfo.setMenuInfo(this);
				SaturnMenuManager.getInstance().addMenuInfosList(itemInfo);
			}
		}

		this.initialMenuItemRoots();
	}

	public List<IMuneItemInfo> getRootMenuItemInfos() {
		return roots;
	}

	public List<IMuneItemInfo> getChildrenMenuItemInfos(String parentId) {
		List<IMuneItemInfo> children = new LinkedList<IMuneItemInfo>();

		if (this.menuItemInfos != null && parentId != null) {

			for (IMuneItemInfo menuItemInfo : this.menuItemInfos) {

				if (menuItemInfo != null) {

					if (parentId.equals(menuItemInfo.getParentId())) {
						children.add(menuItemInfo);
					}
				}
			}
		}
		Collections.sort(children);
		return children;
	}

	private void initialMenuItemRoots() {
		this.roots = new LinkedList<IMuneItemInfo>();

		if (this.menuItemInfos != null) {

			for (IMuneItemInfo menuItemInfo : this.menuItemInfos) {

				if (menuItemInfo != null) {

					if (menuItemInfo.getParentId() == null
							|| "".equals(menuItemInfo.getParentId())) {

						roots.add(menuItemInfo);
					}
				}
			}
		}
		Collections.sort(this.roots);
	}
}
